package com.ht.api.call.func.impl.event;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;

import java.util.HashMap;
import java.util.Map;

/**
 * 事件统一查询
 */
public class EventQueryFunctionCall implements IFunctionCall {

    @Override
    public String getName() {
        return "事件统一查询";
    }

    @Override
    public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
        String sql = """
                
                SELECT 'task' `type`, event_type, event_key,
                SUM(CASE WHEN relation_id IS NOT NULL THEN	1 ELSE 0 END ) num,
                SUM(CASE WHEN relation_id IS NULL THEN	1 ELSE 0 END ) globalnum
                 FROM event_ops_task_config WHERE sys_deleted = 1 GROUP BY event_type, event_key
                
                UNION ALL
                
                SELECT 'effect' `type`, event_type, event_key,
                SUM(CASE WHEN relation_id IS NOT NULL THEN	1 ELSE 0 END ) num,
                SUM(CASE WHEN relation_id IS NULL THEN	1 ELSE 0 END ) globalnum
                 FROM event_effect_config WHERE sys_deleted = 1 GROUP BY event_type, event_key
                
                UNION ALL
                
                SELECT 'plan' `type`, p.event_type, p.event_key,
                SUM(CASE WHEN a.relation_id IS NOT NULL THEN	1 ELSE 0 END ) num,
                SUM(CASE WHEN a.relation_id IS NULL THEN	1 ELSE 0 END ) globalnum
                 FROM event_ad_plan_config p LEFT JOIN event_ad_config a ON a.main_id = p.config_id WHERE p.sys_deleted = 1 GROUP BY p.event_type, p.event_key
                
                 UNION ALL
                
                SELECT 'users' `type`, event_type, event_key, SUM(sys_deleted) num, 0 globalnum
                FROM event_trigger_user_log WHERE sys_deleted = 1 GROUP BY event_type, event_key
                
                """;


        DbList list = Db.query(me.getDataSource(), sql);

        Map<String, Entity> groupMap = new HashMap<>();
        for (Entity entity : list) {
            String eventType = entity.getStr("event_type");
            String eventKey = entity.getStr("event_key");
            String type = entity.getStr("type");
            groupMap.put(type + eventType + eventKey, entity);
        }

        String groupsql = """
                SELECT
                  g.group_name,
                  g.main_id group_id,
                	t.event_type,
                	t.`name` event_type_name,
                	e.event_key,
                	e.event_name event_key_name
                FROM
                	sys_event e
                	LEFT JOIN sys_event_type t ON e.event_type_id = t.main_id
                	LEFT JOIN sys_group g ON t.group_id = g.main_id
                WHERE
                	t.sys_deleted = 1
                	AND e.sys_deleted = 1
                
                """;

        JSONArray groupids = param.getJSONArray("group_id");
        if (groupids != null) {
            groupsql += " AND t.group_id in ("+groupids.join(",")+")";
        }

        groupsql += """
                ORDER BY
                  g.sys_time ASC,
                	t.order_num ASC,
                	t.sys_time ASC,
                	e.order_num ASC
                """;

        DbList groupList = Db.query(groupsql);

        JSONObject groups = JSONUtil.createObj();
        for (Entity entity : groupList) {
            String groupId = entity.getStr("group_id");

            JSONObject group = groups.getJSONObject(groupId);
            if (group == null) {
                group = JSONUtil.createObj();
                group.set("group_name", entity.getStr("group_name"));
                group.set("event_types", JSONUtil.createObj());
                groups.set(groupId, group);
            }

            JSONObject eventTypes = group.getJSONObject("event_types");
            String eventTypeId = entity.getStr("event_type");
            String eventTypeName = entity.getStr("event_type_name");
            JSONObject eventType = eventTypes.getJSONObject(eventTypeId);
            if (eventType == null) {
                eventType = JSONUtil.createObj();
                eventType.set("event_type", eventTypeId);
                eventType.set("event_type_name", eventTypeName);
                eventType.set("event_keys", JSONUtil.createArray());
                eventTypes.set(eventTypeId, eventType);
            }

            JSONArray eventKeys = eventType.getJSONArray("event_keys");
            String eventKeyId = entity.getStr("event_key");
            String eventKeyName = entity.getStr("event_key_name");
            JSONObject eventKey = JSONUtil.createObj();
            eventKey.set("event_key", eventKeyId);
            eventKey.set("event_key_name", eventKeyName);

            eventKey.set("is_global", "未配置");
            JSONObject taskData = groupMap.get("task" + eventTypeId + eventKeyId);
            eventKey.set("task_num", taskData == null ? 0 : taskData.getInt("num"));
            if (taskData != null && taskData.getInt("globalnum") > 0) {
                eventKey.set("is_global", "已配置");
            }

            JSONObject effectData = groupMap.get("effect" + eventTypeId + eventKeyId);
            eventKey.set("effect_num", effectData == null ? 0 : effectData.getInt("num"));
            if (effectData != null && effectData.getInt("globalnum") > 0) {
                eventKey.set("is_global", "已配置");
            }

            JSONObject planData = groupMap.get("plan" + eventTypeId + eventKeyId);
            eventKey.set("plan_num", planData == null ? 0 : planData.getInt("num"));
            if (planData != null && planData.getInt("globalnum") > 0) {
                eventKey.set("is_global", "已配置");
            }

            JSONObject userData = groupMap.get("users" + eventTypeId + eventKeyId);
            eventKey.set("user_num", userData == null ? 0 : userData.getInt("num"));

            eventKeys.add(eventKey);
        }

        return JSONUtil.createObj().set("data", groups);
    }
}
